var config = require('./config.js');
var util = require('./util.js');
var $ = require('webpack-zepto');
import Modal from './modal.js';

function WeixinPay(){

    this.weixinPay = function(orderId,callback){
        if (typeof WeixinJSBridge == "undefined"){
            if( document.addEventListener ){
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            }else if (document.attachEvent){
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
        }else{
            var token = util.storage().get(util.appId());
            $.ajax({
                url : config.path('wechat/payment',['?uToken=' + token, '&order_id=' + orderId]),
                type : 'get',
                success : function(resp){
                    if(!resp.status){
                        onBridgeReady(resp,callback);
                    }else if(resp.status == 503 && resp.err == '3002'){
                        Modal.modal({
                            isSuccess : false,
                            header : '付款失败!',
                            body : '操作太频繁，请一分钟后再试!',
                            centerBtn : {
                                text : '我的订单',
                                isCallback : function () {
                                    var appid = util.getUrlParam('appid');
                                    window.location.href = 'order.html?type=order&appid=' + appid;
                                }
                            },
                            lowerBody : false
                        });
                    }
                }
            });

        }
    };

    this.pay = function(orderId){
        
    };

    function onBridgeReady(resp,callback){
        WeixinJSBridge.invoke('getBrandWCPayRequest',resp,function(res){
            callback.call(this,res);
        });
    };
};

module.exports = new WeixinPay();